package com.zoewin.zephyr.reportjasper.ioc;

import com.zoewin.zephyr.reportjasper.config.ReportConfig;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;

/**
 * Created by Administrator on 2018-11-06.
 */
@Configuration
@EnableAspectJAutoProxy
@PropertySource(value = "classpath:appConfig.properties", ignoreResourceNotFound = true)
public class JasperIOC implements EnvironmentAware {

    /**
     * 模板路径
     */
    private Environment env;
    private HashMap templatePaths = new HashMap();

    /**
     * 模板路径
     */
    private HashMap jasperPaths = new HashMap();

    /**
     * word模板路径
     */
    private HashMap wordPaths = new HashMap();

    /**
     * 图片路径
     */
    private HashMap picPaths = new HashMap();

    @Override
    public void setEnvironment(Environment env) {
        this.env = env;
    }

    @Bean
    public ReportConfig reportConfig() {
        ReportConfig reportConfig = new ReportConfig();
        try {
            //获取jrxmlTemplate文档下所有的文件
            File file = ResourceUtils.getFile("classpath:jrxmlTemplate");
            getFilePath(file);
        } catch (FileNotFoundException e) {
            return reportConfig;
        }
        reportConfig.setPicMap(picPaths);
        reportConfig.setTemplateMap(templatePaths);
        reportConfig.setJasperMap(jasperPaths);
        reportConfig.setWordMap(wordPaths);
        return reportConfig;
    }

    private void getFilePath(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if(files!=null){
                for (File childFile : files) {
                    //递归所有的文件夹
                    getFilePath(childFile);
                }
            }
        } else {
            //当判断为文件的时候将文件名和文件的绝对路径进行保存放入容器
            String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
            String filePath = file.getAbsolutePath();
            if(filePath.contains("pics")){
                picPaths.put(fileName,filePath);
            }else if(filePath.contains("jrxmls")){
                templatePaths.put(fileName,filePath);
            }else if(filePath.contains("jaspers")){
                jasperPaths.put(fileName,filePath);
            }else if(filePath.contains("words")){
                wordPaths.put(fileName,filePath);
            }
        }
    }
}
